package com.pan.download2;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class Write {
    private String dirPath;//写入的文件夹地址
    private String bookName;//书本名称
    private String bookPath;// 书本地址
    private AtomicInteger chapter;//章节

    private FileWriter fileWriter;

    private List<Thread> threadList;//当前的线程

    public void setThreadList(List<Thread> threadList) {
        this.threadList = threadList;
    }

    public String getBookName() {
        return bookName;
    }

    public Write(String bookName){
        this.bookName = bookName;
        dirPath = System.getProperty("user.dir")+"\\story";
        bookPath = dirPath + "\\" +bookName + ".txt";
        chapter = new AtomicInteger(-1);
        //确保文件夹的创建
        File dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdir();
        }
        //确保文件的创建
        File bookFile = new File(bookPath);
        if (!bookFile.exists()){
            try {
                bookFile.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        //创建写入的类
        try {
            this.fileWriter = new FileWriter(bookPath,true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void close(){
        try {
            fileWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 往该文件里面加入下一章节内容
     * @param chapter 章节编号
     * @param content 章节内容
     * @return 是否加入成功
     */
    synchronized public boolean appendNextContent(Integer chapter,String content){
        if (chapter-1==this.chapter.get()){
            this.chapter.set(chapter);
            try {
                fileWriter.write(content);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                Thread nextThread = getNextThread(chapter);
                LockSupport.unpark(nextThread);
                return true;
            }
        }
        return false;
    }

    /**
     * 要唤醒下一章节的线程所在的线程
     * @param chapter 当前的章节编号章节编号
     */
    public Thread getNextThread(Integer chapter){
        int threadNo = (chapter +1) % threadList.size();
        Thread thread = threadList.get(threadNo);
        return thread;
    }
}
